<template>
  <el-container>
    <table-aside ref="tableAsideRef" @node-click="handleNodeClick" v-model:aside-open="asideOpen"
                 v-power="'system:row:lists'"></table-aside>
    <el-container class="is-vertical" v-if="!currentTable">
      <el-empty style="margin-top: 250px;" :image-size="100" description="请单击左侧表结构信息后操作"></el-empty>
    </el-container>
    <el-container class="is-vertical" v-else v-power="'system:column:lists'">
      <el-main class="no-padding">
        <el-form style="padding-right: 10px;" label-width="120px" ref="formRef" :model="currentTable"
                 :rules="formRules">
          <el-tabs type="card" v-model="currentTab">
            <el-tab-pane name="basic" label="基本信息">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="表名称" prop="name">
                    <el-input v-model="currentTable.name" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="表描述" prop="comment">
                    <el-input v-model="currentTable.comment" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="类名称" prop="className">
                    <el-input v-model="currentTable.className" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="作者" prop="functionAuthor">
                    <el-input v-model="currentTable.functionAuthor" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="备注" prop="remark">
                    <el-input v-model="currentTable.remark" clearable type="textarea"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>
            <el-tab-pane name="column" label="列信息">
              <vue-column :sys-column-vo-list="currentTable.sysColumnVoList"></vue-column>
            </el-tab-pane>
            <el-tab-pane name="info" label="生成信息">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="生成模板" prop="categoryId">
                    <el-select v-model="currentTable.categoryId">
                      <el-option :key="item.id" :label="item.name" :value="item.id"
                                 v-for="item in categoryList"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="生成包路径" prop="packageName">
                    <el-input v-model="currentTable.packageName" clearable></el-input>
                    <div class="el-form-item-msg">（生成在哪个 JAVA 包下）</div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="生成模块名" prop="moduleName">
                    <el-input v-model="currentTable.moduleName" clearable></el-input>
                    <div class="el-form-item-msg">
                      （Rest 注解请求路径中的第一部分，用于区分模块所用）<br/>（前台目录的第一层目录）
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="生成业务名" prop="businessName">
                    <el-input v-model="currentTable.businessName" clearable></el-input>
                    <div class="el-form-item-msg">
                      （Rest 注解请求路径中的第二部分，用于区分模块下业务所用） <br/>（前台目录的第二层目录）
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="生成功能名" prop="functionName">
                    <el-input v-model="currentTable.functionName" clearable></el-input>
                    <div class="el-form-item-msg">（类注释、方法注释中显示）</div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="生成代码方式" prop="generatorType">
                    <el-radio v-model="currentTable.generatorType" label="0">压缩包（ZIP）</el-radio>
                    <el-radio v-model="currentTable.generatorType" label="1">自定义路径</el-radio>
                    <div class="el-form-item-msg">（默认为：压缩包（ZIP）下载，也可以自定义生成路径）</div>
                  </el-form-item>
                </el-col>
                <el-col :span="24" v-if="currentTable.generatorType === '1'">
                  <el-form-item label="自定义路径" prop="generatorPath">
                    <el-input v-model="currentTable.generatorPath"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="上级菜单" prop="parentMenuId">
                    <el-tree-select ref="menuTreeSelect" size="large" clearable check-strictly highlight-current
                                    collapse-tags
                                    collapse-tags-tooltip check-on-click-node node-key="id" style="width: 100%"
                                    :render-after-expand="false" :data="menuList" :props="categoryProps"
                                    v-model="currentTable.parentMenuId" placeholder="请选择上级菜单"></el-tree-select>
                    <div class="el-form-item-msg">（分配到指定菜单下）</div>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-divider content-position="left">父子关系</el-divider>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="关联子表" prop="subTableId">
                    <el-select v-model="currentTable.subTableId" @change="tableChange">
                      <el-option :key="table.id" :label="table.comment + '   ' + table.className" :value="table.id"
                                 v-for="table in tableList"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="关联字段" prop="subColumnId">
                    <el-select v-model="currentTable.subColumnId">
                      <el-option :key="column.id" :label="column.comment + '   ' + column.javaField" :value="column.id"
                                 v-for="column in columnList"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>
          </el-tabs>
        </el-form>
      </el-main>
      <el-footer>
        <div class="jcx-table-page">
          <div class="jcx-table-do">
            <el-button type="primary" plain :icon="asideOpen ? 'el-icon-CaretLeft' : 'el-icon-CaretRight'"
                       @click="() => { asideOpen = !asideOpen }"></el-button>
            <el-button type="info" plain @click="handleReset">重 置</el-button>
            <el-button type="success" plain @click="handlePreview">预 览</el-button>
            <el-button type="danger" plain @click="handleDownload">下 载</el-button>
            <el-button plain type="warning" :loading="saving" @click="handleSubmitForm" v-power="'system:row:edit'">
              提 交
            </el-button>
          </div>
        </div>
      </el-footer>
    </el-container>
  </el-container>

  <el-dialog destroy-on-close append-to-body :close-on-click-modal="false" width="1080px" title="代码预览"
             v-model="previewOpen" @closed="handlePreviewCancel">
    <vue-preview :preview="previewResponse"
                 :active-name="currentTable.subTableId ? 'MAIN_JAVA_ACTION' : 'JAVA_ACTION'"></vue-preview>
    <template #footer>
      <el-button plain type="info" @click="handlePreviewCancel">取 消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import tableAside from "./aside.vue";
import vueColumn from "./column.vue";
import vuePreview from "./preview.vue";
import {reactive, ref} from "vue";

import categoryApi from "@/api/generator/category";
import menuApi from "@/api/system/menu";
import treeUtil from "@/utils/tree";
import tableApi from "@/api/generator/row";
import columnApi from "@/api/generator/column";
import modal from "@/utils/modal";

const tableAsideRef = ref(null);
const currentTable = ref(null);
const categoryProps = {
  label: (data) => data.name + "-" + data.code,
  children: 'children',
}
const currentTab = ref('basic');
const formRef = ref();
const categoryList = ref([]);
const menuList = ref([]);
const tableList = ref([]);
const columnList = ref([]);
const asideOpen = ref(true);
const saving = ref(false);
const previewOpen = ref(false);
const previewResponse = ref(null);
const formRules = reactive({
  name: [{required: true, message: "名称为必填项", trigger: "blur"}],
  comment: [{required: true, message: "描述为必填项", trigger: "blur"}],
  className: [{required: true, message: "类名为必填项", trigger: "blur"}],
  functionAuthor: [{required: true, message: "作者为必填项", trigger: "blur"}],
  categoryId: [{required: true, message: "模板分类为必填项", trigger: "blur"}],
  packageName: [{required: true, message: "包名为必填项", trigger: "blur"}],
  moduleName: [{required: true, message: "模块名为必填项", trigger: "blur"}],
  businessName: [{required: true, message: "业务名为必填项", trigger: "blur"}],
  functionName: [{required: true, message: "功能名为必填项", trigger: "blur"}],
  generatorType: [{required: true, message: "生成方式为必填项", trigger: "blur"}],
  generatorPath: [{required: true, message: "生成路径为必填项", trigger: "blur"}],
  parentMenuId: [{required: true, message: "上级菜单为必填项", trigger: "blur"}],
});

const tableChange = (tableId) => {
  console.log(tableId)
  columnApi.lists.get({tableId: tableId, isExtend: true}).then(response => {
    columnList.value = response.data.list;
  });
}

const handleNodeClick = (data) => {
  tableApi.info.get(data.id, true).then(response => {
    currentTable.value = response.data;
    categoryApi.lists.get({enabled: true, isExtend: true}).then(response => {
      categoryList.value = response.data.list;
    });
    menuApi.lists.get({isExtend: true}).then(response => {
      menuList.value = treeUtil.buildTree(response.data.list.filter(item => item.type === 'DIRECTORY'));
    });
    tableApi.lists.get({isExtend: true}).then(response => {
      tableList.value = response.data.list;
    });
    if (currentTable.value.subTableId) {
      columnApi.lists.get({tableId: currentTable.value.subTableId, isExtend: true}).then(response => {
        columnList.value = response.data.list;
      });
    }
  });
}

const handleReset = () => {
  currentTab.value = 'basic';
  asideOpen.value = true;
  currentTable.value = null;
  saving.value = false;
  categoryList.value = [];
  menuList.value = [];
  tableList.value = [];
  columnList.value = [];
}

const handlePreview = () => {
  tableApi.preview.get(currentTable.value.id).then(response => {
    modal.message(response.message, {type: response.status ? 'success' : 'error'});
    if (response.status) {
      previewResponse.value = response.data;
      previewOpen.value = true;
    }
  });
}

const handleDownload = () => {
  tableApi.download.get(currentTable.value.id, currentTable.value.comment);
}

const handlePreviewCancel = () => {
  previewOpen.value = false;
}

const handleSubmitForm = () => {
  // 修改
  saving.value = true;
  currentTable.value.editSysColumnList = currentTable.value.sysColumnVoList;
  tableApi.edit.put(currentTable.value).then(response => {
    modal.message(response.message, {type: response.status ? 'success' : 'error'})
    saving.value = false;
    if (response.status) {
      tableAsideRef.value.getList();
      handleReset();
    }
  })
}
</script>